(function() {
// Just support browser on IOS device and Android.
function checkSupport() {
  var ua = navigator.userAgent;
  var supportedPlatformPattern = /iPad|iPhone|iPod|Android/g;
  return supportedPlatformPattern.test(ua) &&
    (window.DeviceOrientationEvent || window.TouchEvent);
}

//if (!checkSupport()) {
//  Message.setMainInfo(Message.get('browserNotSupported'));
//  return;
//}

function isBrowserSupportTransform3D() {
  var ua = navigator.userAgent;
  var iosBrowserPattern = /(?:iPad|iPhone|iPod).+OS\s(\d)/;
  var androidBrowserPattern = /Android\s(\d)/;
  var matchIos = iosBrowserPattern.exec(ua);
  var matchAndroid = androidBrowserPattern.exec(ua);
  return (matchIos && matchIos[1] >= 4) ||
    (matchAndroid && matchAndroid[1] >= 3);
}

$('#throw').on('click', function() {
  var result = Client.throwDice();
  if (result)
    Message.showMainInfo(Message.get('throwResult', result));
});

var Client = {
  playerRole: null, // A or B
  socket: null,
  throwFlag: false, // throw dice flag
  throwMode: 'shake',

  init: function() {
    Message.setMainInfo(Message.get('clientWelcome'));
    Socket.connect();
    this.registerEvent();
    this.registerThrowEvent();
  },

  registerEvent: function() {
    $('#reload').on('click', function() {
      window.location.reload();
    });
  },

  registerThrowEvent: function() {
    if (window.DeviceOrientationEvent) {
      this.throwMode = 'shake';
      var minAlpha = Infinity;
      var maxAlpha = -Infinity;
      var minBeta = Infinity;
      var maxBeta = -Infinity;
      var minGamma = Infinity;
      var maxGamma = -Infinity;
      var increment = 65;
      
      window.addEventListener('deviceorientation', function(e) {
        var alpha = e.alpha;
        var beta = e.beta;
        var gamma = e.gamma;
        
        if (Client.throwFlag) {
          if (alpha < minAlpha)
            minAlpha = alpha;
          if (alpha > maxAlpha)
            maxAlpha = alpha;

          if (beta < minBeta)
            minBeta = beta;
          if (beta > maxBeta)
            maxBeta = beta;

          if (gamma < minGamma)
            minGamma = gamma;
          if (gamma > maxGamma)
            maxGamma = gamma;
          
          if (maxAlpha - minAlpha >= increment ||
              maxBeta - minBeta >= increment ||
              maxGamma - minGamma >= increment) {
//            $('#info').html('min alpha: ' + minAlpha + '， max alpha: ' + maxAlpha +
//            '<br>minBeta: ' + minBeta + '， maxBeta: ' + maxBeta +
//            '<br>minGamma: ' + minGamma + '， maxGamma: ' + maxGamma + '<br>-----------<br>' +
//            $('#info').html());
            
            minAlpha = Infinity;
            maxAlpha = -Infinity;
            minBeta = Infinity;
            maxBeta = -Infinity;
            minGamma = Infinity;
            maxGamma = -Infinity;
            
            var result = Client.throwDice();
            if (result)
              Message.setMainInfo(Message.get('throwResult', result));
          }
        }
      }, false);
    } else if (window.TouchEvent) {
      this.throwMode = 'touch';
      
      var startClientX;
      var startClientY;
      var MIN_TOUCH_LENGTH = 200; // in pixel

      document.addEventListener('touchmove', function(e) {
        var touches = e.touches.item(0);
        if (!startClientX)
          startClientX = touches.clientX;
        if (!startClientY)
          startClientY = touches.clientY;
      }, false);

      document.addEventListener('touchend', function(e) {
        var touches = e.changedTouches.item(0);
        var endClientX = touches.clientX;
        var endClientY = touches.clientY;
        var xMoved = endClientX - startClientX;
        var yMoved = endClientY - startClientY;
        if (Math.abs(xMoved) >= MIN_TOUCH_LENGTH ||
            Math.abs(xMoved) >= MIN_TOUCH_LENGTH ||
            Math.sqrt(xMoved * xMoved + yMoved * yMoved) >= MIN_TOUCH_LENGTH) {
          var result = Client.throwDice();
          if (result)
            Message.setMainInfo(Message.get('throwResult', result));
        }
        startClientX = null;
        startClientY = null;
      }, false);
    }
  },

  handleLogin: function(data) {
    var result = data.result;
    var role = data.name;
    if (result == 'player_number_limit') {
      Socket.disconnect();
      Message.setMainInfo(Message.get('waiting'));
      this.showReloadButton(Message.get('retry'));
    } else if (result == 'login_success') {
      this.playerRole = role;
      this.showPlayerRole(role);
      this.hideConnectButton();
    }
  },

  startGame: function() {
    this.hideConnectButton();
    Message.setMainInfo(Message.get('gameStart'));
  },

  handleThrowRequest: function() {
    var msgKey = this.throwMode == 'shake' ? 'throwByShake' : 'throwByTouch';
    Message.setMainInfo(Message.get(msgKey));
    this.hideConnectButton();
    this.throwFlag = true;
  },

  throwDice: function() {
    if (this.throwFlag) {
      Client.throwFlag = false;
      var result = Math.round(Math.random() * 5 + 1);
      Socket.throwDice(result);
      if (isBrowserSupportTransform3D()) {
        Dice.throwDice(result);
      } else {
        this.showStaticDice(result);
      }
      return result;
    }
  },

  endGame: function(win) {
    this.playerRole = null;
    this.throwFlag = false;
    var message = win ? Message.get('win') : Message.get('loss');
    this.hidePlayerRole();
    Message.setMainInfo(message);
    Client.showReloadButton(Message.get('playAgain'));
  },

  showStaticDice: function(number) {
    $('#static-dice').addClass('show')
      .css('background-image', 'url(../images/dice/' + number + '.png)');
    setTimeout(function() {
      Client.hideStaticDice();
    }, Dice.diceHidingTime);
  },

  hideStaticDice: function() {
    $('#static-dice').removeClass('show');
  },

  showReloadButton: function(text) {
    $('#reload').show();
    $('#reload').html(text);
  },

  hideConnectButton: function() {
    $('#reload').hide();
  },

  showPlayerRole: function(role) {
    var message = Message.get('loginAs', role);
    $('#player-role').show();
    $('#logedAs').html(message);
    $('#player-icon').addClass('player-' + role + '-icon');
  },

  hidePlayerRole: function() {
    $('#player-role').hide();
  },

  handleViewDisconnection: function() {
    Message.setMainInfo(Message.get('viewDisconnection'));
    var buttonText = Message.get('retry');
    this.showReloadButton(buttonText);
    this.hidePlayerRole();
  },

  handleViewNotReady: function() {
    Message.setMainInfo(Message.get('viewNotReady'));
    var buttonText = Message.get('retry');
    this.showReloadButton(buttonText);
    this.hidePlayerRole();
  }
};

Client.init();

window.Client= Client;

})();